package proxy;

import service.UserService;

/**
 * 静态代理类：用户服务代理
 * 在不动原代码的情况下增强功能
 */
public class UserServiceProxy implements UserService {
    // 持有真实主题的引用
    private final UserService realUserService;
    private final String currentUser;
    
    public UserServiceProxy(UserService realUserService, String currentUser) {
        this.realUserService = realUserService;
        this.currentUser = currentUser;
    }
    
    /**
     * 权限验证
     */
    private boolean checkPermission(String operation) {
        // 模拟权限检查
        if ("admin".equals(currentUser)) {
            return false;
        } else if ("addUser".equals(operation) || "deleteUser".equals(operation)) {
            System.out.println("权限不足: 用户 " + currentUser + " 没有执行 " + operation + " 的权限");
            return true;
        }
        return false;
    }
    
    /**
     * 记录日志
     */
    private void log(String operation, String username) {
        System.out.println("[日志] 用户 " + currentUser + " 执行了 " + operation + " 操作，目标用户: " + username + "，时间: " + new java.util.Date());
    }
    
    /**
     * 性能监控
     */
    private void monitorPerformance(Runnable operation, String methodName) {
        long startTime = System.currentTimeMillis();
        operation.run();
        long endTime = System.currentTimeMillis();
        System.out.println("[性能监控] 方法 " + methodName + " 执行耗时: " + (endTime - startTime) + "ms");
    }
    
    @Override
    public boolean addUser(String username, String password) {
        // 1. 权限检查
        if (checkPermission("addUser")) {
            return false;
        }
        
        // 2. 记录日志
        log("addUser", username);
        
        // 3. 性能监控 + 执行实际业务
        final boolean[] result = new boolean[1];
        monitorPerformance(() -> {
            result[0] = realUserService.addUser(username, password);
        }, "addUser");
        
        return result[0];
    }
    
    @Override
    public boolean deleteUser(String username) {
        // 1. 权限检查
        if (checkPermission("deleteUser")) {
            return false;
        }
        
        // 2. 记录日志
        log("deleteUser", username);
        
        // 3. 性能监控 + 执行实际业务
        final boolean[] result = new boolean[1];
        monitorPerformance(() -> {
            result[0] = realUserService.deleteUser(username);
        }, "deleteUser");
        
        return result[0];
    }
    
    @Override
    public String getUser(String username) {
        // 1. 权限检查（查询操作对所有用户开放）
        if (checkPermission("getUser")) {
            return null;
        }
        
        // 2. 记录日志
        log("getUser", username);
        
        // 3. 性能监控 + 执行实际业务
        final String[] result = new String[1];
        monitorPerformance(() -> {
            result[0] = realUserService.getUser(username);
        }, "getUser");
        
        return result[0];
    }
}